package com.baidu.bridge.service.impl;

import com.baidu.bridge.dto.ab.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;


@Slf4j
public class BaseService {

    // ====================== 通用请求处理 ======================

    /**
     * 通用请求执行方法（处理响应解析和异常）
     */
    <T> T executeCall(Call<CommonResponse<T>> call, String operation) {
        try {
            Response<CommonResponse<T>> response = call.execute();
            if (!response.isSuccessful()) {
                String errorMsg = response.errorBody() != null ? response.errorBody().string() : "HTTP请求失败";
                log.error("[{}] 失败，状态码：{}，错误：{}", operation, response.code(), errorMsg);
                throw new RuntimeException(String.format("[%s] 失败，状态码：%d", operation, response.code()));
            }

            CommonResponse<T> body = response.body();
            if (body == null) {
                log.error("[{}] 失败，响应体为空", operation);
                throw new RuntimeException(String.format("[%s] 响应体为空", operation));
            }

            if (body.getCode() != 0) {
                log.error("[{}] 业务错误，Code：{}，Message：{}", operation, body.getCode(), body.getMessage());
                throw new RuntimeException(String.format("[%s] 业务错误：%s", operation, body.getMessage()));
            }

            return body.getResult(); // 提取业务数据（如DepartmentTree或String）
        } catch (IOException e) {
            log.error("[{}] 网络异常：{}", operation, e.getMessage());
            throw new RuntimeException(String.format("[%s] 网络异常", operation), e);
        }
    }
}
